package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.exception.BusinessException;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.mapper.RoleMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.qo.ResultPage;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.utils.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    @Transactional
    public void save(Employee employee,Long[] roleIds) {
        Long id = employee.getId();
        if (id != null) {
            employeeMapper.updateByPrimaryKey(employee);
            //维护中间表关系
            employeeMapper.deleteMiddleTable(id);
            if (!employee.isAdmin() && roleIds != null && roleIds.length > 0) {
                employeeMapper.insertToMiddleTable(id, roleIds);
            }
        } else {
            //新增
            // 新增
            // 生成盐
//            String salt = UUID.randomUUID().toString().substring(0, 4);
//            // 生成密文密码
//            Md5Hash hash = new Md5Hash(employee.getPassword(),salt,3);
//            // 将盐和密文密码设置到用户中。
//            employee.setPassword(hash.toString());
//            employee.setSalt(salt);
            //生成盐
            String salt = UUID.randomUUID().toString().substring(0, 4);
            //生成密码密文
            Md5Hash hash = new Md5Hash(employee.getPassword(), salt, 3);
            //将盐和密码设置到用户中
            employee.setPassword(hash.toString());
            employee.setSalt(salt);
            employeeMapper.insert(employee);
            //维护中间表
            if (!employee.isAdmin() && roleIds != null && roleIds.length > 0) {
                employeeMapper.insertToMiddleTable(employee.getId(), roleIds);
            }
        }
    }


    @Override
    public void delete(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
    }

//    @Override
//    public void update(Employee employee) {
//        employeeMapper.updateByPrimaryKey(employee);
//    }

    @Override
    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    /***
     * 展示所有
     * @return
     */
    @Override
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

    /**
     * 分页
     * @param qo
     * @return
     */
    @Override
    public PageInfo<Employee> query(QueryObject qo) {

        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Employee> employees = employeeMapper.selForList(qo);
        return new PageInfo<>(employees);

    }

    //删除中间表
    @Override
    public void deleteMiddleTable(Long employeeId) {
        employeeMapper.deleteMiddleTable(employeeId);
    }

    /**
     * Ajax账号校验
     * @param username
     * @return
     */
    @Override
    public Boolean checkUsername(String username) {
        return employeeMapper.checkUsername(username)<=0;
    }

//    /**
//     * 账号密码校验
//     * @param username
//     * @param password
//     * @return
//     */
//    @Override
//    public Employee checkUserByUsernameAndPassword(String username, String password) {
//        //账号密码不合法
//        if (StringUtils.isNull(username) || StringUtils.isNull(password)) {
//            throw new BusinessException("账户名密码不能为空");
//        }
//
//        Employee employee = employeeMapper.checkUserByUsernameAndPassword(username, password);
//        if (employee == null) {
//            throw new BusinessException("账号或密码错误");
//        }
//        return employee;
//    }

    //登录
    @Override
    public void login(String username, String password) {
        if (StringUtils.isNull(username) || StringUtils.isNull(password)) {
            throw new BusinessException("账号密码不能为空");
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            throw new BusinessException("账号密码有误");
        } catch (IncorrectCredentialsException e) {
            throw new BusinessException("账号密码有误");
        } catch (Exception e) {
            throw new BusinessException("系统异常,请稍后重试");
        }
        subject.getSession().setAttribute("user_in_session", subject.getPrincipal());
    }

    @Override
    public Employee selectByUsername(String username) {
        return employeeMapper.selectByUsername(username);
    }
}
